/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import datamodel.Category;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

@Stateless
public class CategoryManager{

    @PersistenceContext
    private EntityManager em;
    

    @RolesAllowed({"SystemAdmin","SystemCustomer"})
    public List<Category> getAllCategories() {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Category> query = builder.createQuery(Category.class);
        Root<Category> c = query.from(Category.class);
        query.select(c);
        return em.createQuery(query).getResultList();
    }
    
    @RolesAllowed({"SystemAdmin"})
    public void saveCategory(Category temp) {
        em.persist(temp);
        em.flush();
    }


    @RolesAllowed({"SystemAdmin","SystemCustomer"})
    public Category getCategory(long id) {
        Category c = em.find(Category.class, id);
        System.out.println(c.getName());
        return c;
    }

    @RolesAllowed({"SystemAdmin"})
    public void remove(Category temp) {
        em.remove(temp);
        em.flush();
    }
    
    @RolesAllowed({"SystemAdmin","SystemCustomer"})
    public List<Category> getCategories(List<Long> categories) {
        /*
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Category> query = builder.createQuery(Category.class);
        Root<Category> c = query.from(Category.class);
        query.select(c).where(builder.isTrue(c.get(Category_.id).in(categories)));
        return em.createQuery(query).getResultList();
        */
        return em.createQuery("SELECT c FROM Category c WHERE category_id IN (?1)")
                .setParameter(1, categories)
                .getResultList();
    }
}
